package org.test.threadlocal;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * Created by Hy on 2018/7/11.
 */
public class ProductServiceImpl implements ProductService{
    private static final String UPDATE_PRODUCT_SQL="update product set price =? where id = ?";
    private static final String INSERT_LOG_SQL="insert into log(created,description) values (?,?)";
    public void updateProductPrice(long productId, int price) {
        try {
            //获取连接
            Connection conn = DBUtil.getConn();
            conn.setAutoCommit(false);//关闭自动提交事务（开启事务）

            //执行操作
            updateproduct(conn,UPDATE_PRODUCT_SQL,productId,price);//更新产品
            insertLog(conn,INSERT_LOG_SQL,"Create product.");//插入日志
            
            //提交事务
            conn.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            DBUtil.closeConn();
        }
    }

    private void insertLog(Connection conn, String insertLogSql, String logDescription) throws Exception{
        PreparedStatement pstmt = conn.prepareStatement(insertLogSql);
        pstmt.setString(1,"Hy");
        pstmt.setString(2,logDescription);
        int rows = pstmt.executeUpdate();
        if(rows!=0){
            System.out.println("Insert log success!");
        }
    }

    private void updateproduct(Connection conn, String updateProductSql, long productId, int price) throws Exception{
        PreparedStatement psmt = conn.prepareStatement(updateProductSql);
        psmt.setInt(1,price);
        psmt.setLong(2,productId);
        int rows = psmt.executeUpdate();
        if(rows!=0){
            System.out.println("Update product success!");
        }
    }

    public static void main(String[] args) {
        //1.单独一个线程是没有问题的
//        ProductService productService = new ProductServiceImpl();
//        productService.updateProductPrice(1,3000);
        //2.测试多线程就会出问题了
        for (int i=0;i<10;i++){
            ProductService productService = new ProductServiceImpl();
            ClientThreadTest test = new ClientThreadTest(productService);
            test.start();
        }
    }
}
